class Solution {
public:
    int trap(vector<int>& height) {
        int res=0;
        int leftmax=0,rightmax=0;
        int l=0,r=height.size()-1;
        while(l<r)
        {
            leftmax=max(leftmax,height[l]);
            rightmax=max(rightmax,height[r]);
            if(leftmax<rightmax)
            {
                res+=leftmax-height[l];
                l++;
            }
            else
            {
                res+=rightmax-height[r];
                r--;
            }
        }
        return res;
    }
};
